//
//  Observable+Cache.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/9.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import RxSwift
import Moya

extension ObservableType
where Element: TargetType, Element: Cacheable, Element.ResponseType == Moya.Response {
    // .cache 从请求中取缓存
    public func request() -> Observable<Moya.Response> {
        return flatMap { target -> Observable<Moya.Response> in
            // 将请求的先存一遍
            let source = target.requset().storeCachedResponse(for: target).asObservable()
            
            // 有缓存且允许缓存
            if let response = try? target.cacheResponse(), target.allowsStorage(response) {
                // 拼接到响应前面
                return source.startWith(response)
            }
            
            return source
        }
    }
}
